package com.lxw.report.meta.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * excel 导入监听
 * @param <T>
 */
public class WriterListener<T> extends AnalysisEventListener<T> {
    Logger logger= LoggerFactory.getLogger(WriterListener.class);

    /**
     * 存储表格数据
     */
    private List<T> dataList=new ArrayList<>();

    private Class classZ;

    public WriterListener(List<T> dataList,Class classZ){
        this.dataList=dataList;
        this.classZ=classZ;
    }

    /**
     * 读取每一行数据
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        this.dataList.add(data);
    }

    /**
     * excel读取结束后执行
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    /**
     * 发生错误调用
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
     public void onException(Exception exception, AnalysisContext context){
        try{
            String errorMessage=null;
            if(exception.getCause() instanceof NumberFormatException){
                errorMessage="导入失败 数字格式填写错误："+exception.getMessage();
            }else if(exception.getCause() instanceof DateTimeParseException){
                errorMessage="导入失败 时间格式填写错误："+exception.getMessage();
            }else{
                errorMessage="导入失败 "+exception.getMessage();
            }
            Method generate =  this.classZ.getDeclaredMethod("genErrorTemplate", String.class);
            Object object= generate.invoke(this.classZ.newInstance(),errorMessage);
            this.dataList.add((T)object);
        }catch (Exception e){
            this.dataList.add(null);
        }
    }
}
